<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>测试Gzip</title>
    <style>
        p {
            overflow: auto;
            max-height: 50px;
        }
    </style>
</head>
<body>
<div>
    <span style="font-size: 12px;color: darkgray">内容越长，重复率越高，压缩效果越好，如果字数过少，压缩率可能超过100%</span>
</div>
<textarea id="input" oninput="input()" rows="12" cols="56"></textarea>
<div>
    <p>原文:</p>
    <p id="yw"></p>
</div>
<div>
    <p>压缩:</p>
    <p id="ys"></p>
</div>
<div>
    <p>解压:</p>
    <p id="jy"></p>
</div>
<div>
    <p>压缩率:</p>
    <p id="ysl"></p>
</div>
<script src="https://cdn.staticfile.org/pako/1.0.10/pako.min.js"></script>
<!--如果需要支持那些不自带atob btoa的浏览器，就需要用下面这个包来进行base64-->
<!--<script src="https://cdn.staticfile.org/Base64/1.0.2/base64.min.js"></script>-->
<script>
    function input() {
        const input = document.getElementById('input').value;
        const ys = zip(input);
        const jy = unzip(ys);
        document.getElementById('yw').innerText = input;
        document.getElementById('ys').innerText = ys;
        document.getElementById('jy').innerText = jy;
        document.getElementById('ysl').innerText = (Math.round(length(ys) / length(input) * 10000) / 100.00 + "%");

    }

    // 解压
    function unzip(b64Data) {
        const strData = atob(b64Data);
        const charData = strData.split('').map(function (x) {
            return x.charCodeAt(0);
        });
        const binData = new Uint8Array(charData);
        const data = pako.inflate(binData);
        const array = new Uint16Array(data);
        // 防止一次解压造成内存溢出，这里进行分段解压
        let result = '';
        let i = 0;
        const maxRange = 8 * 1024;
        for (i = 0; i < array.length / maxRange; i++) {
            result += String.fromCharCode.apply(null, array.slice(i * maxRange, (i + 1) * maxRange));
        }
        result += String.fromCharCode.apply(null, array.slice(i * maxRange));
        return decodeURIComponent(result);
    }

    // 压缩
    function zip(str) {
        return btoa(pako.gzip(encodeURIComponent(str), {to: 'string'}));
    }

    // 占用字节数计算(UTF-8)
    function length(str) {
        let total = 0, charCode, i, len;
        for (i = 0, len = str.length; i < len; i++) {
            charCode = str.charCodeAt(i);
            if (charCode <= 0x007f) {
                total += 1;
            } else if (charCode <= 0x07ff) {
                total += 2;
            } else if (charCode <= 0xffff) {
                total += 3;
            } else {
                total += 4;
            }
        }
        return total;
    }
</script>
</body>
</html>
